package com.sora.basic.controller;

import com.sora.basic.util.AjaxResult;
import com.sora.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传 - 需要【请求方式：post】
 * 下载 - 不需要
 * 删除 - 需要【请求方式：delete】
 * 修改 - 不需要 = 先删除再上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {


    /**
     * 文件上传接口
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult uploadFile(@RequestPart MultipartFile file){
        try {
            String oName = file.getOriginalFilename();
            String exeName = oName.substring(oName.lastIndexOf(".") + 1);
            Object fileName = FastDfsUtils.upload(file.getBytes(), exeName);
            return new AjaxResult(true,fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "上传失败！！！");
        }
    }


    /**
     * 删除接口
     * @return
     * delete http://localhost:8080/fastDfs/group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
     * 后端接收：@PathV("/{a}/{b}/{c}/{d}") - 麻烦
     * delete http://localhost:8080/fastDfs?path=/group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
     */
    @DeleteMapping
    public AjaxResult deleteFile(@RequestParam("path") String path){
        try {
            path = path.substring(1);//   group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
            String groupName = path.substring(0, path.indexOf("/"));//group1
            String fileName = path.substring(path.indexOf("/") + 1); //M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
            FastDfsUtils.delete(groupName,fileName);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

}
